#include "manageaccounts.h"
#include "ui_manageaccounts.h"

#include "cashplusplus.h"
#include "readonlycurrencydelegate.h"

ManageAccounts::ManageAccounts(QWidget *parent) :
	Tab(parent),
	m_ui(new Ui::ManageAccounts)
{
	m_ui->setupUi(this);
	m_model = 0;
}

ManageAccounts::~ManageAccounts()
{
	cleanup();
	delete m_ui;
}

void ManageAccounts::cleanup()
{
	if (m_model)
	{
		m_model->submitAll();
		delete m_model;
		m_model = 0;
	}
}

void ManageAccounts::updateContents()
{
	initializeModel();
}

void ManageAccounts::flushData()
{
	if (m_model)
	{
		m_model->submitAll();
	}
}

void ManageAccounts::initializeModel()
{
	cleanup();

	m_model = new AccountModel(this);

	m_ui->accountsView->setModel(m_model);

	// Custom delegates for currency and date/time
	m_ui->accountsView->setItemDelegateForColumn(3, new ReadOnlyCurrencyDelegate(m_ui->accountsView));
	m_ui->accountsView->setItemDelegate(new QSqlRelationalDelegate(m_ui->accountsView));

	// Hide the ID column
	m_ui->accountsView->setColumnHidden(0, true);
}

void ManageAccounts::on_addAccountButton_clicked()
{
	m_model->addAccount();
}

void ManageAccounts::on_deleteAccountButton_clicked()
{
	QModelIndexList currentSelection = m_ui->accountsView->selectionModel()->selectedIndexes();

	if (currentSelection.count() > 0 && QMessageBox::Yes == QMessageBox::question(this, "Delete Account(s)?", "Delete selected account(s)? Doing so will remove all associated transactions.", QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
	{
		m_model->deleteAccounts(currentSelection);
	}
}

void ManageAccounts::slot_updateNDBalances(const double& domer, const double& flex)
{
	m_model->updateNDBalances(domer, flex);
}

void ManageAccounts::changeEvent(QEvent *e)
{
	QWidget::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		m_ui->retranslateUi(this);
		break;
	default:
		break;
	}
}

